/* 刷新页面时重置表单 */
window.onload = function() {
    $("form").each(function(index, element) {
       element.reset();
    });
}

app.controller('loginCtrl', ['$scope', function ($scope) {
    $scope.userName = $.cookie("userKey");
	$scope.password = "";
	
    $scope.login = function () {
        var userName = $.trim($scope.userName);
        var password = $.trim($scope.password);
		var keyType = 1;
		
		var numReg = /^[0-9]+$/;
		var phoneReg = /^[1][34578][0-9]{9}$/;
		var mailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
		var nameReg = /^[\u4E00-\u9FA50-9A-Za-z_-]{3,25}$/;
		var pwdReg = /^[0-9A-Za-z!@#$%&*_-]{6,25}$/;
		if(userName.length == 0) {
			toastr.error("请输入用户名");
			return;
		}
		if(numReg.test(userName)) {
			keyType = 2;
			if (!phoneReg.test(userName)) {
            	toastr.error("手机号码格式不正确！");
            	return;
        	}
		} else if(userName.indexOf('@') >= 0) {
			keyType = 3;
			if(!mailReg.test(userName)) {
				toastr.error("邮箱格式不正确！");
				return;
			}
		} else {
			keyType = 1;
			if(!nameReg.test(userName)) {
				toastr.error("用户名格式不正确！");
				return;
			} else if(Utils.countLength(userName) < 5 || Utils.countLength(userName) > 25) {
				toastr.error("用户名长度不合法！");
				return;
			}
		}
		if(!pwdReg.test(password)) {
			toastr.error("密码格式不正确！");
			return;
		}
		$("#submit-login").prop("disabled", true);
		$("#submit-login").val("正在登录···");
		
        var param = {
            userKey: userName,
            passWord: password,
            keyType: keyType,
        };
        AQ.callAQ("userLogin.do", param, function(result) {
            $scope.$apply(function(){
                $.cookie("userKey", userName, {expires: 30});
				$.cookie("userName", result[1].userName, {expires: 30});
				$.cookie("User", JSON.stringify(result[1]));
				$.cookie("isLogined", 1);
				if(result[1].experience < 30) {
					$.cookie("firstLogin", true);
				}
            });
            var redirectURL = Utils.getUrlParam("redirectURL");
            if(redirectURL != null) {
				 location.replace(redirectURL);
			} else {
				 location.replace("task-center.html");
			}
        }, function(err, code) {
			toastr.error(err);
			$("#submit-login").val("登录");
			$("#submit-login").prop("disabled", false);
        });
    };
	
	
	$("#forget-pwd").click(function() {
		var userName = $("#userName").val();
        location.replace("forget-pwd.html?userName="+ userName);
    });
	
	
}]);
